<?php

namespace app\api\controller;

use app\api\validation\Exchange;
use app\payment\PayFactory;
use app\services\ChatService;
use app\services\CommentService;
use app\services\ExchangeService;
use app\services\FollowingService;
use app\services\PaymentService;
use app\services\UserCollectService;
use plugin\admin\app\model\Option;
use plugin\admin\app\model\UserCollect;
use support\Db;
use support\Request;
use Respect\Validation\Validator as v;
use Yansongda\Pay\Pay;

class ExchangeController
{
    public function list(Request $request)
    {
        try {
            $page = $request->post('page', 1);
            $categoryId = $request->post('category_id', 0);
            $keyword = $request->post('keyword', '');
            $orderType = $request->post('order_type', 1);

            switch ($orderType) {
                default:
                case 1:
                    $order = ['wants_count', 'desc'];
                    break;
                case 2:
                    $order = ['created_time', 'desc'];
                    break;
            }

            return ok_rsp('成功', ExchangeService::list($page, 10, $categoryId, $keyword, $order));
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function show(Request $request)
    {
        try {
            $id = $request->post('id');

            if (!$id) {
                throw new \Exception('不存在的换物');
            }

            return ok_rsp('成功', ExchangeService::show($id));
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function categoryList(Request $request)
    {
        try {
            return ok_rsp('成功', ExchangeService::indexCategories());
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function deployUserAvatars(Request $request)
    {
        try {
            $type = $request->post('type', 'exchange');

            return ok_rsp('成功', ExchangeService::deployUserAvatars());
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function guessYouLikeList(Request $request)
    {
        try {
            $page = $request->post('page', 1);

            return ok_rsp('成功', ExchangeService::guessYouLikeList($page, 10));
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }

    }

    public function qualityList()
    {
        try {
            $item = Option::where('name', "dict_quality")->first();
            $values = json_decode($item['value'], true);
            $values = array_column($values, 'value');
            return ok_rsp('成功', $values);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function hotSearchList()
    {
        try {
            $item = Option::where('name', "dict_hot_search")->first();
            $values = json_decode($item['value'], true);
            $values = array_column($values, 'value');
            return ok_rsp('成功', $values);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function userList(Request $request)
    {
        try {
            $page = $request->post('page', 1);
            $keyword = $request->post('keyword');
            $data = ExchangeService::userList($page, 10, $keyword);

            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function detail(Request $request)
    {
        $id = $request->post('id');

        try {
            if (empty($id)) {
                throw new \Exception('不存在的ID');
            }

            return ok_rsp('成功', ExchangeService::detail($id));
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function follow(Request $request)
    {
        try {
            $userId = $request->post('user_id');

            FollowingService::follow($userId);
            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function cancelFollow(Request $request)
    {
        try {
            $userId = $request->post('user_id');

            FollowingService::cancelFollow($userId);
            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function mobile(Request $request)
    {
        $id = $request->post('id');
        $payWay = $request->post('pay_way', PayFactory::BALANCE);

        try {
            if (empty($id)) {
                throw new \Exception('不存在的ID');
            }

            if ($payWay != PayFactory::WECHAT) {
                PaymentService::checkPayPassword($request->post('pay_password'));
            }

            $data = ExchangeService::payAndGetContactMobile($id, $payWay);

            return ok_rsp('获取联系人电话成功', $data);
        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    public function getMobile(Request $request)
    {
        $id = $request->post('id');

        try {
            if (empty($id)) {
                throw new \Exception('不存在的ID');
            }

            $data = ExchangeService::getExchangeMobile($id);

            return ok_rsp('获取联系人电话成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function comment(Request $request)
    {
        Db::beginTransaction();
        try {
            $id = $request->post('id');
            $commentId = $request->post('comment_id', 0);
            $content = $request->post('content');

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            if (empty(trim($content))) {
                throw new \Exception('评论内容不能为空');
            }

            $data = CommentService::add($id, $content, $commentId);

            Db::commit();
            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            Db::rollBack();
            return err_rsp($e->getMessage());
        }
    }

    public function commentList(Request $request)
    {
        try {
            $id = $request->post('id');
            $page = $request->post('page', 1);

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            $list = CommentService::list($id, $page, 10);

            return ok_rsp('成功', $list);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function likeComment(Request $request)
    {
        try {
            $id = $request->post('id');

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            CommentService::likeComment($id);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function cancelLikeComment(Request $request)
    {
        Db::beginTransaction();
        try {
            $id = $request->post('id');

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            CommentService::cancelLikeComment($id);

            Db::commit();
            return ok_rsp('成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return err_rsp($e->getMessage());
        }
    }

    public function likeExchange(Request $request)
    {
        try {
            $id = $request->post('id');

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            ExchangeService::likeExchange($id);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function confirmReservation(Request $request)
    {
        try {
            $orderNo = $request->post('order_no');

            $date = $request->post('date');

            if ($date > date('Y-m-d', strtotime('+4 days'))) {
                throw new \Exception('不允许的预约时间');
            }

            $timeRange = $request->post('time_range');

            $times = ExchangeService::timeList();

            if (!in_array($timeRange, $times)) {
                throw new \Exception('不允许的预约时间');
            }

            ExchangeService::confirmReservation($orderNo, $request->post('express_id'), $date, $timeRange, $request->post('address_id'));

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function cancelLikeExchange(Request $request)
    {
        Db::beginTransaction();
        try {
            $id = $request->post('id');

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            ExchangeService::cancelLikeExchange($id);

            Db::commit();
            return ok_rsp('成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return err_rsp($e->getMessage());
        }
    }

    public function collectExchange(Request $request)
    {
        try {
            $id = $request->post('id');

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            ExchangeService::collectExchange($id);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function reportTypeList(Request $request)
    {
        try {
            $item = Option::where('name', "dict_report_type")->first();
            $values = json_decode($item['value'], true);
            $values = array_column($values, 'value');
            return ok_rsp('成功', $values);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function reservationTimeList(Request $request)
    {
        try {
            $times = ExchangeService::timeList();

            $todayList = [];
            $list = [];
            $currentTime = date('H:i');
            foreach ($times as $time) {
                $list[] = [
                    'time' => $time,
                    'disable' => true
                ];

                $temp = explode('-', $time);

                $todayList[] = [
                    'time' => $time,
                    'disable' => $currentTime > $temp[0] && $currentTime < $temp[1]
                ];
            }

            $data = [
                [
                    'label' => '今天',
                    'date' => date('Y-m-d'),
                    'list' => $todayList
                ],
                [
                    'label' => '明天',
                    'date' => date('Y-m-d', strtotime('+1 days')),
                    'list' => $list
                ],
                [
                    'label' => '后天',
                    'date' => date('Y-m-d', strtotime('+2 days')),
                    'list' => $list
                ],
                [
                    'label' => date('m-d', strtotime('+3 days')) . ' ' . getWeek(strtotime('+3 days')),
                    'date' => date('Y-m-d', strtotime('+3 days')),
                    'list' => $list
                ],
                [
                    'label' => date('m-d', strtotime('+4 days')) . ' ' . getWeek(strtotime('+4 days')),
                    'date' => date('Y-m-d', strtotime('+4 days')),
                    'list' => $list
                ]
            ];



            return ok_rsp('成功', $data);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function report(Request $request)
    {
        try {
            $id = $request->post('id');
            $data = $request->post();

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            if ($data['type_text'] == '') {
                throw new \Exception('反馈类型不能为空');
            }

            if ($data['content'] == '') {
                throw new \Exception('反馈内容不能为空');
            }

            if (!is_array($data['thumbs']) || count($data['thumbs']) == 0) {
                throw new \Exception('反馈图片不能为空');
            }

            ExchangeService::report($id, $data);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function applyExchange(Request $request)
    {
        Db::beginTransaction();
        try {
            $id = $request->post('id');
            $data = $request->post();
            $addressId = $request->post('address_id');

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            if ($data['name'] == '') {
                throw new \Exception('商品名称不能为空');
            }

            if ($data['desc'] == '') {
                throw new \Exception('商品描述不能为空');
            }

            if (!is_array($data['thumbs']) || count($data['thumbs']) == 0) {
                throw new \Exception('商品图片不能为空');
            }

            if ($data['quality'] == '') {
                throw new \Exception('商品成色不能为空');
            }

            ExchangeService::applyExchange($id, $data, $addressId);

            Db::commit();
            return ok_rsp('成功');
        } catch (\Exception $e) {
            Db::rollBack();
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    public function cancelCollectExchange(Request $request)
    {
        try {
            $id = $request->post('id');

            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            ExchangeService::cancelCollectExchange($id);

            return ok_rsp('成功');
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }


    public function add(Request $request)
    {
        Db::beginTransaction();
        $data = $request->post();

        try {
            $validate = (new Exchange());
            if (!$validate->check($data)) {
                throw new \Exception($validate->getError());
            }

            $id = ExchangeService::add($data);

            Db::commit();
            return ok_rsp("成功", ['id' => $id]);
        } catch (\Exception $e) {
            Db::rollBack();
            return err_rsp($e->getMessage());
        }
    }

    public function edit(Request $request)
    {
        Db::beginTransaction();
        $data = $request->post();

        try {
            $id = $request->post('id');
            if (empty($id)) {
                throw new \Exception('ID不能为空');
            }

            $validate = (new Exchange());
            if (!$validate->check($data)) {
                throw new \Exception($validate->getError());
            }

            ExchangeService::edit($id, $data);

            Db::commit();
            return ok_rsp("成功");
        } catch (\Exception $e) {
            Db::rollBack();
            return err_rsp($e->getMessage());
        }
    }

    public function categories(Request $request)
    {
        try {
            $pid = $request->post('pid', 0);
            $categories = ExchangeService::getCategories($pid);
            $guessYouLikeCategories = ExchangeService::guessYouLikeCategories($pid, $categories);
            return ok_rsp('获取易物类型成功', ['categories' => $categories, 'guess' => $guessYouLikeCategories]);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function guessYouLikeCategories(Request $request)
    {
        try {
            $pid = $request->post('pid', 0);
            $categories = ExchangeService::getCategories($pid);
            $guessYouLikeCategories = ExchangeService::guessYouLikeCategories($pid, $categories);
            return ok_rsp('成功', ['guess' => $guessYouLikeCategories]);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }

    public function allCategories(Request $request)
    {
        try {
            $categories = ExchangeService::getAllCategories();
            return ok_rsp('成功', ['categories' => $categories]);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }
}